package org.issaclu.springbootmybatis.user.service;

import org.issaclu.springbootmybatis.user.bo.UserDetailBo;
import org.issaclu.springbootmybatis.user.dto.UserDetail;
import org.issaclu.springbootmybatis.user.dto.UserInfo;
import org.issaclu.springbootmybatis.user.mapper.UserDetailMapper;
import org.issaclu.springbootmybatis.user.mapper.UserInfoMapper;
import org.issaclu.springbootmybatis.util.Utils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserDetailService {
    private final UserDetailMapper userDetailMapper;
    private final UserInfoMapper userInfoMapper;

    public UserDetailService(UserDetailMapper userDetailMapper,
                             UserInfoMapper userInfoMapper) {
        this.userDetailMapper = userDetailMapper;
        this.userInfoMapper = userInfoMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    public UserDetailBo insert(UserDetailBo detail, byte[] avatar) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(Utils.uuid());
        userInfo.setUserName(detail.getUserName());
        userInfo.setBirthday(detail.getBirthday());
        userInfo.setAge(detail.getAge());
        userInfo.setAvatar(avatar);
        userInfo.setIntroductionText(detail.getIntroductionText());

        UserDetail userDetail = new UserDetail();
        userDetail.setUserId(userInfo.getId());
        userDetail.setLevel(detail.getLevel());
        userDetail.setSex(detail.getSex());
        userDetail.setBirthday(detail.getBirthday());
        this.userInfoMapper.insertUser(userInfo);
        this.userDetailMapper.insertUserDetail(userDetail);
        detail.setId(userDetail.getId());
        return detail;
    }
}
